package com.sxbang.bms.config.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import java.io.UnsupportedEncodingException;
import java.security.Key;
import java.util.Base64;
import java.util.Date;

/**
 * @author lmm
 * @date 2019/4/12 0012  15:51.
 */
public class JwtUtils {
    final static String SECRET = "WH#$%(!)(#*!()!KL<55$6><MQLMNQNQJQK EiLCJuYW1lIjoif>?N<:{LWPW";

    /**
     * 生成的密钥
     */
    final static Key base64EncodedSecretKey = generalSecretKey(SignatureAlgorithm.HS256, SECRET);

    final static long TOKEN_EXP = 1000 * 60 * 60 *24;//过期时间, 1000 * 60测试使用60秒

    /**
     * 生成key，用于生成token
     *
     * @param signatureAlgorithm 指定加密算法
     * @param secretKey          自定义秘钥，仅仅后台知道
     * @return Key
     */
    public static Key generalSecretKey(SignatureAlgorithm signatureAlgorithm, String secretKey) {
        // 在Java 8在java.util包下面实现了BASE64编解码API，API简单易懂
        byte[] base64EncodedSecretKey = null;
        try {
            base64EncodedSecretKey = Base64.getEncoder().encode(secretKey.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 这样也是可以的 Key key = MacProvider.generateKey()
        if (base64EncodedSecretKey == null) {
            throw new IllegalArgumentException();
        }
        return new SecretKeySpec(base64EncodedSecretKey, signatureAlgorithm.getJcaName());
    }

    public static String getToken(String userName) {
        return Jwts.builder()
                .setSubject(userName)
                .claim("username", userName)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXP)) /*过期时间*/
                .signWith(SignatureAlgorithm.HS256, base64EncodedSecretKey)
                .compact();
    }

    //解析token
    public static void checkToken(String token) throws ServletException {
        try {
            final Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();
            //System.out.println("从token中解析到的username=="+claims);
            String username= (String) claims.get("username");
            //System.out.println("username=="+username);
        } catch (ExpiredJwtException e1) {
            throw new ServletException("token expired");
        } catch (Exception e) {
            throw new ServletException("other token exception");
        }
    }

}
